import os,pathlib,hashlib
from utils import SettingUtil
from datetime import datetime

__OLD_MD5_MAP__ = {}
__CUR_MD5_MAP__ = {}
__TAB_MAP__=None


def readTextFile(fileName:str)->str:
    content:str = ""
    with open(fileName,"r",encoding="utf8") as f:
        content = f.read()
    return content

def writeTextFile(fileName:str,content:str)->None:
    with open(fileName,"w+",encoding="utf8") as f:
        f.write(content)

def listRootExcels(root:str,excelFiles,oldTables,oldTableMap):
    global __OLD_MD5_MAP__
    __OLD_MD5_MAP__ = readMD5MetaMap()
    rootFiles = os.listdir(root)
    excelExts = SettingUtil.getSetting().excelExt
    for f in rootFiles:
        url = os.path.join(root,f)
        if os.path.isfile(url):
            ext = os.path.splitext(url)[1]
            if ext in excelExts and not os.path.split(url)[1].startswith("~$") and checkFileChangeByMD5(url):
                excelFiles.append(url)
                if url in oldTableMap:
                    oldTables.extend(oldTableMap[url])
        elif os.path.isdir(url):
            listRootExcels(url,excelFiles,oldTables,oldTableMap)
    

def checkFileChangeByMD5(fileName):
    global __OLD_MD5_MAP__
    global __CUR_MD5_MAP__
    newMD5 = getFileMD5(fileName)
    __CUR_MD5_MAP__[fileName] = newMD5
    if fileName not in __OLD_MD5_MAP__: #新增
        return True
    oldMD5 = __OLD_MD5_MAP__[fileName]
    return oldMD5 != newMD5

def getFileMD5(fileName)->str:
    hexStr = ""
    with open(fileName,"rb") as f:
        md5 = hashlib.md5()
        md5.update(f.read())
        hexStr = md5.hexdigest()
    return hexStr

#读取proto文件的模板
def getProtoTemp():
    return readTextFile(SettingUtil.getSetting().protoTemp)

def getMessageTemp():
    return readTextFile(SettingUtil.getSetting().msgTemp)

def readMD5MetaMap()->dict:
    md5Map = {}
    md5MetaFile = SettingUtil.getSetting().md5MetaFile
    if os.path.exists(md5MetaFile):
        with open(md5MetaFile,"r",encoding="utf8") as f:
            lines = f.readlines()
            for line in lines:
                if line.strip() == "":
                    continue
                kvArr = line.split("=")
                if len(kvArr)!=2:
                    continue
                md5Map[kvArr[0].strip()] = kvArr[1].strip()
                
    return md5Map

def writeCurMD5Map():
    global __CUR_MD5_MAP__
    writeMD5MetaMap(__CUR_MD5_MAP__)

def writeMD5MetaMap(md5Map):
    lines = []
    for item in md5Map:
        lines.append(item+"="+md5Map[item]+"\n")
    with open(SettingUtil.getSetting().md5MetaFile,"w",encoding="utf8") as f:
        f.writelines(lines)

def readConfigTableMap()->dict:
    global __TAB_MAP__
    if __TAB_MAP__ == None:
        oldTableMap = {}
        configMetaFile = SettingUtil.getSetting().configMetaFile
        if os.path.exists(configMetaFile):
            with open(configMetaFile,"r",encoding="utf8") as f:
                for line in f.readlines():
                    arr = line.strip().split("=")
                    tbName = arr[0]
                    fileName = arr[1]
                    if fileName not in oldTableMap:
                        oldTableMap[fileName] = []
                    oldTableMap[fileName].append(tbName)
        __TAB_MAP__ = oldTableMap
    return __TAB_MAP__

def writeConfigTableSet(tableSet):
    lines = []
    for item in tableSet:
        lines.append(item+"\n")
    with open(SettingUtil.getSetting().configMetaFile,"w",encoding="utf8") as f:
        f.writelines(lines)

def writePBFile(fileName,pbBytes:bytes):
    with open(fileName,"wb") as f:
        f.write(pbBytes)


def toProtoContent(message):
    content = getProtoTemp()
    content = content.replace(r"$message$",message)
    dateStr = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    content = content.replace(r"$dateTime$",dateStr)
    return content